﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Matrix.MaKaYunShang.BLL;
using Matrix.MaKaYunShang.Model;
using Matrix.MaKaYunShang.Model.Dto;

namespace Matrix.MaKaYunShang.McMagWeb
{
    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
    public class PermissionFilterAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var hasRight = false;
            var controller = (string) filterContext.RouteData.Values["controller"];
            var action = (string) filterContext.RouteData.Values["action"];
            var currentAccount = HttpContext.Current.Session["McAccounts"] as McAccountDto;

            var allowedModules = GetAllowedModules(currentAccount);

            if (currentAccount != null && (allowedModules != null && currentAccount.RoleId != 1))
            {
                foreach (var t in allowedModules)
                {
                    if (String.Equals(t.Controller, controller, StringComparison.CurrentCultureIgnoreCase) &&
                        String.Equals(t.Action, action, StringComparison.CurrentCultureIgnoreCase))
                    {
                        hasRight = true;
                        break;
                    }
                }
            }
            else
            {
                // 如果是超级用户 直接返回 获取所有操作权限
                hasRight = true;
            }

            if (hasRight)
                return;

            filterContext.HttpContext.Response.Write("<script type='text/javascript'>alert('无访问权限，请联系您的上级管理员！'); location.href = '/Home/Index';</script>");
            filterContext.Result = new EmptyResult();
        }

        /// <summary>
        /// 获取当前用户所有有权限执行的动作
        /// </summary>
        /// <returns></returns>
        private List<McModules> GetAllowedModules(McAccountDto accountInfo)
        {
            var lsModuleIds = McRoleModulePermissionBLL.Instance.GetModelListByRoleIdAndShopId(accountInfo.ShopId, accountInfo.RoleId).Select(x=>x.ModuleId).ToList();

            return lsModuleIds.Select(moduleId => McModulesBLL.Instance.GetModel(moduleId)).ToList();
        }
    }
}